package test.crane;

import ptolemy.actor.*;
import ptolemy.kernel.*;
import ptolemy.kernel.util.*;
import ptolemy.data.*;
import ptolemy.data.type.*;

//////////////////////////////////////////////////////////////////////////
//// powerUp
/**

@author Ivan Jeukens
@version v 0.1 07/02/2002
*/
public class powerUp extends TypedAtomicActor {

    public powerUp(CompositeEntity container, String name) throws
            IllegalActionException, NameDuplicationException {
        super(container, name);

        powerOn = new TypedIOPort(this,  "powerOn", true, false);
        powerOn.setTypeEquals(BaseType.GENERAL);

        shutdown = new TypedIOPort(this, "shutdown", true, false);
        shutdown.setTypeEquals(BaseType.GENERAL);

        emstop = new TypedIOPort(this, "emstop", true, false);
        emstop.setTypeEquals(BaseType.GENERAL);

        start = new TypedIOPort(this, "start", false, true);
        start.setTypeEquals(BaseType.GENERAL);

         new Attribute(this, "_nonStrictMarker");
    }

    public TypedIOPort powerOn;
    public TypedIOPort shutdown;
    public TypedIOPort emstop;

    public TypedIOPort start;

    ///////////////////////////////////////////////////////////////////
    ////                         public methods                    ////

     public void pruneDependencies() {
        super.pruneDependencies();
        removeDependency(shutdown, start);
        removeDependency(emstop, start);
    }

    public void initialize() throws IllegalActionException {
        super.initialize();
        _state = _READY;
    }

    public void fire() throws IllegalActionException {
        if(powerOn.isKnown() && !start.isKnown()) {
        //  if(powerOn.isKnown()) {
            if(powerOn.hasToken(0) && (_state == _READY)) {
                start.broadcast(new Token());
            }
        }

        if(powerOn.isKnown() && !start.isKnown()) {
            start.broadcastClear();
        }
    }

    public boolean postfire() throws IllegalActionException {
        if(_state == _READY) {
            if(powerOn.isKnown()) {
                if(powerOn.hasToken(0)) {
                    _state = _RUNNING;
                }
            }
        }
        else
        if(_state == _RUNNING) {
            if(shutdown.isKnown()) {
                if(shutdown.hasToken(0)) {
                    _state = _READY;
                }
            }
            if(emstop.isKnown()) {
                if(emstop.hasToken(0)) {
                    _state = _READY;
                }
            }
        }

        return true;
    }

    ///////////////////////////////////////////////////////////////////
    ////                        private methods                    ////

    ///////////////////////////////////////////////////////////////////
    ////                      private variables                    ////

    private int _state;

    private static final int _READY = 1;
    private static final int _RUNNING = 2;
}
